<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\index\controller;
use think\swoole\Server;
/**
 * Task控制器
 * @package app\index\controller
 */
class Task extends Home
{
    public function index()
    {
        $serv = new \swoole_server(config('swoole.host'),config('swoole.port'));

        $serv->set([
            'task_worker_num' => config('swoole.task_worker_num')
        ]);

        //此回调函数在worker进程中执行
        $serv->on('Receive', function($serv, $fd, $reactor_id, $data) {
            //投递异步任务
            $task_id = $serv->task($data);
            echo "Dispatch AsyncTask: id={$task_id}\n";
            echo "----------task begin---------".PHP_EOL;
        });

        //处理异步任务(此回调函数在task进程中执行)
        $serv->on('Task', function ($serv, $task_id, $reactor_id, $data) {
            echo "New AsyncTask[id={$task_id}]".PHP_EOL;
            $data=json_decode($data,true);
            foreach ($data as $val){
                send_email($val['last_name'].' '.$val['first_name'],$val['title'],$val['content'],$val['email']);
                echo "邮箱".$val['email'].'发送成功'.PHP_EOL;
            }
            //返回任务执行的结果
            $serv->finish("OK");
        });

        //处理异步任务的结果(此回调函数在worker进程中执行)
        $serv->on('Finish', function ($serv, $task_id, $data) {
            echo "AsyncTask[{$task_id}] Finish: {$data}".PHP_EOL;
            echo "----------task end---------".PHP_EOL;
        });

        $serv->start();
    }


}
